$(function(){
	if(!IS_AUTH){
		$_GET['user_id'] = ME_ID;
	}
	if(!$_GET['action'] || $_GET['action'] == 'search'){
		$.showSearch(ADMIN_URL+'posts.html?action=search');
	}else{
		$.showSearch(null);
	}

	var postListTbody = $('#post-list-table>tbody');
	var EditorMenu = { //编辑页面菜单
			'放弃': function(){
				if(typeof localStorage != 'undefined'){
					/** 清除本地存储数据 */
					for(var i in localStorage){
						if($_GET['action'] == 'add' && i.indexOf('post_new_') === 0){
							localStorage.removeItem(i);
						}else if($_GET['action'] == 'update' && i.indexOf('post_id_') ===0){
							var id = parseInt(i.substr(8)),
								name = i.substr(8+id.toString().length+1);
							if(id == postId.val()){
								localStorage.removeItem(i);
							}
						}
					}
				}
				history.back(-1);
			},
			'提交': function(){
				/** 提交文章编辑表单 */
				$('#post-edit-form').find(':submit').click();
			}
		},
		ListMenu = { //列表页面菜单
			'排序': {
				'按最新排序': function(){
					$_GET = $.extend($_GET, {page: 1, orderby: 'post_time', sequence: 'desc'});
					location.search = '?'+$.param($_GET);
				},
				'按 ID 排序': function(){
					$_GET = $.extend($_GET, {page: 1, orderby: 'post_id', sequence: 'asc'});
					location.search = '?'+$.param($_GET);
				}
			},
			'上一页': function(){
				$_GET['page'] -= 1;
				getPostList();
			},
			'下一页': function(){
				$_GET['page'] += 1;
				getPostList();
			},
			'修改': {
				'编辑': function(){
					var id = postListTbody.find('.active').eq(0).data('id');
					location.search = '?action=update&post_id='+id;
				},
				'删除': function(){
					postListTbody.editMulti({
						obj: 'post',
						act: 'delete',
						unit: '篇',
						action: '删除',
						item: '文章',
						callback: function(){
							getPostList(true);
						}
					});
				},
				'移动目录': function(){
					$('#change-category-modal').one('shown.bs.modal', function(){
						$(this).find('select').focus();
					}).modal('show');
				}
			}
		},
		showListMenu = function(){ //显示列表菜单
			if(!TOTAL || TOTAL == 1){
				var menu = null;
			}else if($_GET['page'] == 1 && $_GET['page'] == PAGES){
				var menu ={'排序': ListMenu['排序']};
			}else if($_GET['page'] == 1){
				var menu ={
					'排序': ListMenu['排序'],
					'下一页': ListMenu['下一页']
				};
			}else if($_GET['page'] == PAGES){
				var menu ={
					'排序': ListMenu['排序'],
					'上一页': ListMenu['上一页']
				};
			}else{
				var menu = {
					'排序': ListMenu['排序'],
					'上一页': ListMenu['上一页'],
					'下一页': ListMenu['下一页']
				}
			}
			var length = postListTbody.find('.active').length;
			if(length){
				if(menu == null){
					menu = $.extend({}, ListMenu['修改']);
				}else{
					menu['修改'] = $.extend({}, ListMenu['修改']);
					if(length > 1) delete menu['修改']['编辑'];
				}
			}
			$.showMenu(menu);
		},
		getPostList = function(noAlert){ //获取文章列表数据
			var act = $_GET['action'] == 'search' ? 'search' : 'getMulti';
			var url = SITE_URL+'mod.php?obj=post&act='+act+'&'+$.param($_GET);
			$.ajax({
				url: url, 
				success: function(result){
					postListTbody.html('');
					if(result.success){
						var data = result.data,
							id = 1 + ($_GET['page'] - 1) * $_GET['limit'];
						for(var i in data){
							var html = '<tr data-id="'+data[i]['post_id']+'"><td>'+id+'</td><td><a title="查看" target="_blank" href="'+(data[i]['post_link'] || create_url(POST_STATIC_URL, data[i]))+'">'+data[i]['post_title']+'</a></td>';
							if(!$_GET['user_id']){
								html += '<td><a title="查看此人的文章" href="posts.html?user_id='+data[i].user_id+'&tablist=person">'+(data[i]['user_nickname'] || data[i]['user_name'])+'</a></td>';
							}
							html += '<td>'+date('Y-m-d', data[i]['post_time']*1000)+'</td><td data="category-name">'+(data[i]['category_alias'] || data[i]['category_name'])+'</td><td>'+(data[i]['post_comments'] ? '<a title="查看详情" href="comments.html?post_id='+data[i]['post_id']+'">'+data[i]['post_comments']+'</a>' : '无')+'</td></tr>';
							postListTbody.append(html);				
							id++;
						}
						TOTAL = result.total;
						PAGES = result.pages;
						showListMenu();
					}else if(!noAlert){
						alert(result.data);
					}
				},
				error: function(xhr){
					alert('与服务器的连接出现错误，文章获取失败。');
					console.log(xhr.responseText);
				}
			});
		};

	/** 根据查询参数显示指定菜单 */
	if($_GET['action'] == 'add' || $_GET['action'] == 'update'){
		var postId = $('#post-edit-form').find('input[name="post_id"]'),
			storeBaseName = postId.length ? 'post_id_'+postId.val()+'_' : 'post_new_';
		$.showMenu(EditorMenu);
		$('#post_title').focus();
	}else{
		showListMenu();

		/** 点击列表项时对其进行高亮 */
		postListTbody.on('click', 'td', function(event){
			$(this).closest('tr').toggleClass('active');
			showListMenu();
		});

		/** 更改目录模态框 */
		var modal = $('#change-category-modal');
		modal.find(':submit').click(function(){
			var catId = parseInt(modalBody.find('select').val());
			if(catId > 0){
				postListTbody.editMulti({
					obj: 'post',
					act: 'update',
					data: {category_id: catId},
					unit: '篇',
					action: '移动',
					item: '文章',
					once: false,
					callback: function(data){
						var catName = modalBody.find('select').find('option[value="'+catId+'"]').text();
						$(this).find('td[data="category-name"]').text(catName);
						modal.modal('hide');
					}
				});
			}else{
				alert('请选择分类目录。');
			}
		});
	}

	$('#post-content-div').summernote({
		height: 400,
		lang: 'zh-CN',
		dialogsFade: true,
		placeholder: '书写你的文章...',
		callbacks: {
			onImageUpload: function(image){
				$.upload({
					url: SITE_URL+'mod.php?file::upload',
					file: image,
					data: {file_desc: '用于文章的图片。'},
					name: 'file[]',
					success: function(result){
						if(result.success){
							$.each(result.data, function(i, n){
								if(n.error){
									alert(n.name+' 上传失败: '+n.error);
								}else{
									var image = $('<img>').attr('src', n.file_src);
									$('#post-content-div').summernote('insertNode', image[0]);
									if(i == 0 && !$('#post_thumbnail').val()){
										$('#post_thumbnail').val(n.file_src);
									}
								}
							});
						}else{
							if(typeof result.data != 'string'){
								$.each(result.data, function(i, n){
									alert(n.name+' 上传失败: '+n.error);
								});
							}else{
								alert(result.data);
							}
						}
					},
					error: function(xhr){
						alert('与服务器的连接出现错误，文件上传失败。');
						console.log(xhr.responseText);
					}
				});
			},
			onChange: function(content) {
				$('#post_content').val(content);
				if(typeof localStorage != 'undefined') localStorage.setItem(storeBaseName+'post_content', content);
 			}
		}
	});
	$('#post-edit-form').ajaxSubmit({
		success: function(result){
			if(result.success){
				if(typeof localStorage != 'undefined'){
					for(var i in localStorage){
						if($_GET['action'] == 'add' && i.indexOf('post_new_') === 0){
							var name = i.substr(9);
							localStorage.removeItem(i);
						}else if($_GET['action'] == 'update' && i.indexOf('post_id_') === 0){
							var id = parseInt(i.substr(8)),
								name = i.substr(8+id.toString().length+1);
							if(id == result.data.post_id){
								localStorage.removeItem(i);
							}
						}
					}
				}
				if($_GET['action'] == 'add'){
					alert('添加成功。')
					location.search = '?post_id='+result.data.post_id;
				}else{
					alert('修改成功。');
					history.go(-1);
				}
			}else{
				alert(result.data);
			}
		},
		error: function(xhr){
			if(typeof localStorage != 'undefined'){
				alert('与服务器的连接出现问题，数据已保存到本地并等待下一次提交。');
			}else{
				alert('与服务器的连接出现问题，请将数据保存到本地并尝试再次提交。');
			}
			console.log(xhr.responseText);
		}
	});

	/** 切换分类目录 */
	$('#change-category').on('change', function(){
		if($(this).val() == 0){
			delete $_GET['category_id'];
		}else{
			$_GET['category_id'] = $(this).val();
		}
		$_GET['page'] = 1;
		$_GET['tablist'] = 'category';
		location.search = '?'+$.param($_GET);
	});

	if($_GET['action'] == 'add'){
		if($_GET['category_id']){
			$('#category_id').find('option[value="'+$_GET['category_id']+'"]').attr('selected', true);
		}
		if($_GET['post_type']){
			$('#post_type').find('option[value="'+$_GET['post_type']+'"]').attr('selected', true);
		}
	}

	if(typeof localStorage != 'undefined' && ($_GET['action'] == 'add' || $_GET['action'] == 'update')){
		for(var i in localStorage){
			if(i.indexOf('post_new_') === 0 && $_GET['action'] == 'add'){
				var name = i.substr(9);
				if($.inArray(name, ['post_title', 'post_tags', 'post_link']) >=0){
				 	$('#'+name).val(localStorage[i]);
				}else if(name == 'post_content'){
				 	$('#post_content').val(localStorage[i]);
				 	$('.note-editable').html(localStorage[i]);
				}else if(name == 'category_id' || name == 'post_type'){
					$('#'+name).children('option[value="'+localStorage[i]+'"]').attr('selected', true).siblings().attr('selected', false);
				}
			}else if(i.indexOf('post_id_') === 0 && $_GET['action'] == 'update'){
				var id = parseInt(i.substr(8)),
					name = i.substr(8+id.toString().length+1);
				if(id == postId.val()){
					if($.inArray(name, ['post_title', 'post_tags', 'post_link']) >= 0){
					 	$('#'+name).val(localStorage[i]);
					}else if(name == 'post_content'){
					 	$('#post_content').val(localStorage[i]);
					 	$('.note-editable').html(localStorage[i]);
					}else if(name == 'category_id' || name == 'post_type'){
						$('#'+name).children('option[value="'+localStorage[i]+'"]').attr('selected', true).siblings().attr('selected', false);
					}
				}
			}
		}
		$('#post-edit-form').find('input[id]').on('input', function(){
			localStorage.setItem(storeBaseName+$(this).attr('name'), $(this).val());
		}).each(function(){
			localStorage.setItem(storeBaseName+$(this).attr('name'), $(this).val());
		});
		$('#post-edit-form').find('select[id]').change(function(){
			localStorage.setItem(storeBaseName+$(this).attr('name'), $(this).val());
		});
		localStorage.setItem(storeBaseName+'category_id', $('#category_id').val());
		localStorage.setItem(storeBaseName+'post_type', $('#post_type').val());
		localStorage.setItem(storeBaseName+'post_content', $('#post-content-div').html());
	}
});